package com.lzp.spring.data.datasourcedemo;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @description: 数据源测试类，使用嵌入式数据库
 * @author: lzp
 * @createTime: 2021-11-17 00:00
 **/
@SpringBootApplication
@Slf4j // 生成日志字段 log ！！CommandLineRunner:项目启动后执行的功能
public class DataSourceDemoApplication implements CommandLineRunner {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public static void main(String[] args) {
        SpringApplication.run(DataSourceDemoApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        showConnection();
        showData();
    }

    /**
     * 打印数据源信息：连接、连接池，springboot根据h2数据库自动配置
     * http://localhost:8080/actuator/beans
     *
     * @throws SQLException
     */
    private void showConnection() throws SQLException {
        log.info(dataSource.toString());
        Connection conn = dataSource.getConnection();
        log.info(conn.toString());
        conn.close();
    }

    private void showData() {
        jdbcTemplate.queryForList("SELECT * FROM FOO")
                .forEach(record -> log.info(record.toString()));
    }
}
